/**
* @file main.c
* @Name: the main function
* @author W. P. Yao, ywp@pku.edu.cn
* @version 0.0.1
* @date 2015-12-09
*/
#include "Head.h"
#include "Datatype.h"
#include "Mem_Alloc.h"
#include "Init.h"
#include "Itera.h"
#include "Result.h"
#include "Mem_Free.h"


/**
* @Name: err_handler 
*
* @Param: comm
* @Param: err_code
* @Brief: comment on the error message when debug code 
*/
void err_handler(MPI_Comm * comm, int * err_code, ...)
{
	int resultlen;
	char err_string[MPI_MAX_ERROR_STRING];
	MPI_Error_string(*err_code, err_string, &resultlen);
	printf("MPI exception caughted: error code %d\n", *err_code);
	printf("\terror: %s\n", err_string);
	MPI_Abort(*comm, *err_code);
}

/**
* @Name: main 
*
* @Param: argc
* @Param: argv[]
*
* @Returns: 
*/
int main(int argc, char * argv[])
{
	MPI_Init(&argc, &argv);							///MPI init
	MPI_Errhandler_create(&err_handler, &errhdl);
	MPI_Errhandler_set(MPI_COMM_WORLD, errhdl);
	MPI_Comm_rank(MPI_COMM_WORLD, &myrank);		    ///rank ID
	MPI_Comm_size(MPI_COMM_WORLD, &sum_rank);       ///rank num
	
	starttime = MPI_Wtime();						///start time
	START = 0;
	END   = 2*PI;									///space
	NUM   = 80;										///grid num
	DH    = (END-START)/(NUM-1);					///h
	
	Inset_N = NUM/2;							    ///inset grid num
	Add_NUM = NUM+Inset_N;							///grid num during FFT
	DH_t    = 0.8/NUM;								///h in t

	Step_Max = 3.16/DH_t;				 			///max step in t
	M        = NUM/sum_rank;
	Add_M    = Add_NUM/sum_rank;

	if(myrank == 0){
		printf("The total iteration step is %d\n",
		Step_Max);									///print run time
	}

	//============================================
	Mem_Alloc();									///allocate memory
	//============================================
	Init();											///initialization
	//============================================
	RK4();											///4th Runge Kutta itera in t
	//============================================
	Result(0);										///output result
	//============================================
	Mem_Free();										///free memory
	//============================================


	endtime  = MPI_Wtime();
	duration = endtime - starttime;				///total run time

	MPI_Finalize();									///end of MPI

	if(myrank == 0){
		printf("\nThe run time is %f\n", duration); ///print run time
		printf("\nThe total grids = 1.5*NUM = %d\n",
			NUM*3/2);								///print grids num
		printf("\nThe time step = %f\n", DH_t);     ///print step num
	}

	return 0;
}
